package com.example.emos.wx.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    /**
     * 设置静态资源映射
     *
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 框架默认的StringHttpMessageConverter编码是ISO-8859-1
     * @Response注解当接口返回的是字符串时会中文乱码
     *
     * @return
     */
    public HttpMessageConverter<String> stringResponseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 请注意顺序，因为其实底层就是用list进行存储的所有可以通过指定下标来指定顺序
        // 目前这种写法可以解决问题，但是因为我们指定的StringHttpMessageConverter
        // 框架也指定了StringHttpMessageConverter，所有我们要将自己的排在前面，否者依然无法使用自定义的消息转换器
        super.extendMessageConverters(converters);
        converters.add(0, stringResponseBodyConverter());
    }
}
